package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.dto.customizedcc.GroupUserAndRids;
import com.tvunetworks.center.user.mapper.CustomizedUserGroupMapper;
import com.tvunetworks.center.user.model.CustomizedUserGroup;
import com.tvunetworks.center.user.model.param.AddGroupParam;
import com.tvunetworks.center.user.model.param.PageCustomizedUserGroupParam;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.CustomizedUserGroupVo;
import com.tvunetworks.center.user.service.CustomizedUserDeviceGroupService;
import com.tvunetworks.center.user.service.CustomizedUserGroupService;
import com.tvunetworks.center.user.service.UserDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: tvucc-aggregator
 * @description: CustomizedUserGroupServiceImpl
 * @author lebronchen
 * @create: 2020-03-13 08:49
 **/
@Service
@Slf4j
public class CustomizedUserGroupServiceImpl extends BaseService<CustomizedUserGroup> implements CustomizedUserGroupService {

    @Autowired
    private CustomizedUserGroupMapper customizedUserGroupMapper;
    @Autowired
    private CustomizedUserDeviceGroupService customizedUserDeviceGroupService;
    @Autowired
    private UserDeviceService userDeviceService;

    @Override
    @Transactional
    public void addGroup(AddGroupParam param) {
        boolean isDefault = param.getDefaultGroup() != null && param.getDefaultGroup().intValue() == 1;
        this.addGroup(param.getUserId(), param.getGroup(), isDefault, param.isAllowRepetition());
    }

//    @Override
//    @Transactional
//    public void setDefaultGroup(AddGroupParam param) {
//        CustomizedUserGroup userGroup = this.getUserGroup(param.getUserId(), param.getGroup());
//        if (userGroup == null) {
//            // 用户不存在该 group
//            ServerException.Exception(ResultConstant.CustomizedUserGroup.USER_NOT_EXIST_GROUP);
//        }
//        // 把其他分组设置为不是默认
//        customizedUserGroupMapper.setUserAllGroupNotDefault(param.getUserId());
//
//        userGroup.setDefaultGroup(1);
//        super.updateSelective(userGroup);
//    }

    @Override
    public PageInfo<CustomizedUserGroupVo> listUserGroup(PageCustomizedUserGroupParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<CustomizedUserGroupVo> list = customizedUserGroupMapper.listUserGroup(param);
        return new PageInfo<>(list);
    }

    @Override
    public CustomizedUserGroup getById(String id) {
        return super.selectExistByPrimaryKey(id);
    }

    @Override
    public String getUserDefaultGroupName(String userId) {
        CustomizedUserGroup userGroup = this.getUserDefaultGroup(userId);
        if (userGroup == null) {
            log.error("getUserDefaultGroupName return null userId:{}", userId);
            return null;
        }
        return userGroup.getGroup();
    }

    @Override
    public CustomizedUserGroup getUserDefaultGroup(String userId) {
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setUserId(userId)
                .setDefaultGroup(1);
        return super.selectExistOne(record);
    }

    @Override
    @Transactional
    public void deleteGroup(String userId, String id) {
        CustomizedUserGroup exist = this.getById(id);
        if (exist == null) {
            // Group 不存在
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_NOT_EXIST);
        }
        if (!StringUtils.equals(userId, exist.getUserId())) {
            // Group 不属于当前用户
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_NOT_BELONG_USER);
        }
        if (exist.getDefaultGroup() == 1) {
            // 默认分组，不能删除
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_IS_DEFAULT_CAN_NOT_DELETE);
        }
        boolean groupExistDevice = customizedUserDeviceGroupService.isGroupExistDevice(id);
        if (groupExistDevice) {
            // Group 里有设备，不能删除
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_EXIST_DEVICE_CAN_NOT_DELETE);
        }
        super.deleteLogicById(id);
    }

    @Override
    public void updateGroup(String userId, AddGroupParam param) {
        CustomizedUserGroup exist = this.getById(param.getId());
        if (exist == null) {
            // Group 不存在
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_NOT_EXIST);
        }
        if (!StringUtils.equals(userId, exist.getUserId())) {
            // Group 不属于当前用户
            ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_NOT_BELONG_USER);
        }

        if (StringUtils.isNotEmpty(param.getGroup()) && !StringUtils.equalsIgnoreCase(param.getGroup(), exist.getGroup())) {
            // 修改 Group Name
            this.checkGroupName(param.getUserId(), param.getGroup(), param.isAllowRepetition());
            exist.setGroup(param.getGroup());
        }

        if (param.getDefaultGroup() != null && param.getDefaultGroup() == 1 && exist.getDefaultGroup() == 0) {
            // 设置为默认分组
            // 把其他分组设置为不是默认
            customizedUserGroupMapper.setUserAllGroupNotDefault(param.getUserId());
            exist.setDefaultGroup(1);
        }
        super.updateSelective(exist);
    }

    private void checkGroupName(String userId, String group, boolean allowRepetition) {
        boolean userExistGroup = this.isUserExistGroup(userId, group);
        if (userExistGroup) {
            // 用户不能拥有相同的 group
            ServerException.Exception(ResultConstant.CustomizedUserGroup.USER_EXIST_GROUP);
        }

        if (!allowRepetition) {
            boolean groupExist = this.isGroupExist(group);
            if (groupExist) {
                // 不能出现相同的 group
                ServerException.Exception(ResultConstant.CustomizedUserGroup.GROUP_EXIST);
            }
        }
    }

    private void addGroup(String userId, String group, boolean isDefault, boolean allowRepetition) {
        this.checkGroupName(userId, group, allowRepetition);

        boolean userHaveGroup = this.isUserHaveGroup(userId);
        if (!userHaveGroup && !isDefault) {
            // 如果用户没有分组，那么第一个分组设置为默认分组
            isDefault = true;
        }

        if (isDefault) {
            // 如果设置为默认分组，那么把其他分组设置为不是默认
            customizedUserGroupMapper.setUserAllGroupNotDefault(userId);
        }

        int defaultGroup = isDefault ? 1 : 0;
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setUserId(userId)
                .setGroup(group)
                .setDefaultGroup(defaultGroup);
        super.insert(record);
    }

    private CustomizedUserGroup getUserGroup (String userId, String group) {
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setUserId(userId)
                .setGroup(group);
        return super.selectExistOne(record);
    }

    private boolean isUserHaveGroup (String userId) {
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setUserId(userId);
        List<CustomizedUserGroup> list = super.selectExistList(record);
        return !CollectionUtils.isEmpty(list);
    }


    private boolean isUserExistGroup(String userId, String group) {
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setUserId(userId)
                .setGroup(group);
        List<CustomizedUserGroup> list = super.selectExistList(record);
        return !CollectionUtils.isEmpty(list);
    }

    @Override
    public boolean isGroupExist(String group) {
        CustomizedUserGroup record = new CustomizedUserGroup()
                .setGroup(group);
        List<CustomizedUserGroup> list = super.selectExistList(record);
        return !CollectionUtils.isEmpty(list);
    }

    @Override
    public List<String> listGroupUser(String group) {
        return customizedUserGroupMapper.listGroupUser(group);
    }

    @Override
    public GroupUserAndRids getGroupUserAndRids(String group) {
        GroupUserAndRids result = new GroupUserAndRids();
        List<String> userIds = this.listGroupUser(group);
        if (CollectionUtils.isEmpty(userIds)) {
            return result;
        }
        Set<String> rids = new HashSet<>();
        for (String userId : userIds) {
            List<String> userRids = userDeviceService.listUserCacheRids(userId);
            if (!CollectionUtils.isEmpty(userIds)) {
                rids.addAll(userRids);
            }
        }
        result.setUserIds(userIds)
                .setRids(rids);
        return result;
    }

    @Override
    public String getGroupNameById(String id) {
        CustomizedUserGroup userGroup = this.getById(id);
        if (userGroup == null) {
            return null;
        }
        return userGroup.getGroup();
    }

    @Override
    public String getGroupNameByUserDevice(String userId, String peerId) {

        return null;
    }
}
